﻿// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System.Net.Http.Headers;
using System.Text;

namespace System.Net.Http
{
  /// <summary>HTTP Basic Authentication authorization header</summary>
  /// <seealso cref="System.Net.Http.Headers.AuthenticationHeaderValue" />
  public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
  {
    /// <summary>Initializes a new instance of the <see cref="BasicAuthenticationHeaderValue"/> class.</summary>
    /// <param name="userName">Name of the user.</param>
    /// <param name="password">The password.</param>
    public BasicAuthenticationHeaderValue(string userName, string password)
      : base("Basic", EncodeCredential(userName, password))
    {
    }

    private static string EncodeCredential(string userName, string password)
    {
      if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName));
      if (password == null) { password = ""; }

      return Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}"));
    }
  }
}